package com.gitee.feizns.quickstart.spring.data.jpa.page;

import com.gitee.feizns.quickstart.domain.page.PageRecordsVo;
import com.gitee.feizns.quickstart.domain.page.PageVo;
import org.springframework.data.domain.Page;

import java.util.List;

/**
 * spring data {@link Page} 转换为 {@link PageRecordsVo}
 * @author feizns
 * @since 2022/10/18
 */
public class SpringDataPageRecordsVoImplImpl<T> implements PageRecordsVo<T> {

    /**
     * {@link Page}
     */
    private final Page<T> page;

    public SpringDataPageRecordsVoImplImpl(Page<T> page) {
        this.page = page;
    }

    @Override
    public PageVo getPage() {
        return new PageVo() {
            @Override
            public Long getSize() {
                long size = page.getSize();
                return size == PageVo.LARGEST_PAGE_SIZE ? size : getTotal();
            }

            @Override
            public Long getPages() {
                return (long) page.getTotalPages();
            }

            @Override
            public Long getCurrent() {
                return (long) page.getPageable().getPageNumber();
            }

            @Override
            public Long getTotal() {
                return page.getTotalElements();
            }

        };
    }

    @Override
    public List<T> getRecords() {
        return page.getContent();
    }

}
